package com.heima.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.PageResult;
import com.heima.pojo.Sku;
import com.heima.pojo.SkuClass;
import com.heima.pojo.vo.SkuClassVo;
import com.heima.service.ISkuClassService;
import com.heima.service.ISkuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/vm-service/skuClass")
@Api(tags = "商品分类管理")
public class SkuClassController {
    @Autowired
    private ISkuClassService skuClassService;
    @Autowired
    private ISkuService skuService;

    @PostMapping
    @ApiOperation("添加商品分类")
    public Boolean addSkuClass(@RequestBody SkuClassVo skuClassVo) {
        if (ObjectUtil.isEmpty(skuClassVo)) {
            return false;
        }
        return skuClassService.save(BeanUtil.toBean(skuClassVo, SkuClass.class));
    }

    @GetMapping("/search")
    @ApiOperation("商品分类列表")
    public PageResult<SkuClassVo> search(PageResult<SkuClassVo> pageResult, @RequestParam(required = false) String className) {
        return skuClassService.search(pageResult, className);
    }

    @GetMapping("/{classId}")
    @ApiOperation("根据id查询商品分类")
    public SkuClassVo getSkuClassById(@PathVariable Integer classId) {
        SkuClass skuClass = skuClassService.getById(classId);
        return BeanUtil.toBean(skuClass, SkuClassVo.class);
    }

    @PutMapping("/{classId}")
    @ApiOperation("修改商品分类")
    public Boolean updateSkuClass(@PathVariable Integer classId, @RequestBody SkuClassVo skuClassVo) {
        if (ObjectUtil.isEmpty(classId) || ObjectUtil.isEmpty(skuClassVo)) {
            return false;
        }
        LambdaUpdateWrapper<SkuClass> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SkuClass::getClassId, classId);
        return skuClassService.update(BeanUtil.toBean(skuClassVo, SkuClass.class), wrapper);
    }

    @DeleteMapping("/{classId}")
    @ApiOperation("删除商品分类")
    public Boolean deleteSkuClass(@PathVariable Integer classId) {
        if (ObjectUtil.isEmpty(classId)) {
            return false;
        }
        LambdaQueryWrapper<Sku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Sku::getClassId, classId);
        if (skuService.count(wrapper) > 0) {
            return false;
        }
        return skuClassService.removeById(classId);
    }
}
